import { User as UserUtils } from '../../utils/user'
import {
  noConsole
} from '../../config';
import LoginService from '../../services/login'

const loginService = new LoginService()
const userUtils = new UserUtils()

export default {
  namespace: 'login',
  state: {
    // 发送短信后的重发倒数秒数
    curTimerCount: 0,
    // 短信验证码发送定时器
    codeTimer: null,
  },
  effects: {
      // 搜索银行产品
    * login({ payload }, {call, put, select}) {
        
        const { code, data } = yield call(loginService.login.bind(loginService), payload.mobile, payload.code)
        // console.log('code = ', code)
        // console.log('data = ', data)
        if (code === 0) {
          // 记录登录时间
          const userInfo = data
          userInfo.loginDate = new Date()
          userInfo.mobile = payload.mobile
          let update = userInfo
          const old = userUtils.getUserFromLocalStorage()
          // console.log('old = ', old)
          if (old) {
            update = Object.assign(old, userInfo)
          }
          // console.log('update = ', update)
          // 保存用户信息到缓存
          userUtils.saveUserToLocalStorage(update)

          // 更新 userInfo
          yield put({ type: 'common/save', payload: { userInfo: update } })
          // 更新用户登录状态
          yield put({ type: 'common/save', payload: { isLoginAlready: userUtils.isLogin() } })
          yield put({ type: 'common/save', payload: { isLoginValid: userUtils.isLoginValid() } })

          // 执行回调方法
          if (payload.callback) {
            payload.callback.call()
          }
        }

        // setTimeout(() => {
        //   // 执行回调方法
        //   if (payload.callback) {
        //     payload.callback.call()
        //   }
        // }, 2000)
      },
  },
  reducers: {
    // 更新state
    save(state, { payload }) {
      return {...state, ...payload};
    },
  },
};
